function upload(title, content) {
    var xhr = new XMLHttpRequest()

    xhr.open("post", `/studio/track/record.json?title=${title}`)  // 最终结果由json处理
    xhr.onload = function () {
        console.log(this.status)
        console.log(this.responseText)
    }
    xhr.send(content)
}

window.onload = function () {
    if (!navigator.mediaDevices.getUserMedia) {
        alert("浏览器版本过于古老，不支持媒体访问，请更新浏览器至较新版本！")
        return
    }

    // var constraints = { audio: true, video: true}
    var constraints = { audio: true }
    var promise = navigator.mediaDevices.getUserMedia(constraints)

    // stream的类型是 MediaStream（媒体流）
    function onSuccess(stream) {
        alert("用户授权麦克风权限成功")
        // console.log(stream)
        // var oAudio = document.querySelector('audio')
        // oAudio.srcObject = stream

        // var oVideo = document.querySelector('video')
        // oVideo.srcObject = stream

        var mediaRecorder = new MediaRecorder(stream)
        mediaRecorder.onstart = function () {
            console.log("开始录制")
        }

        var data = []
        mediaRecorder.ondataavailable = function (evt) {
            console.log('数据可用')
            console.log(evt)
            data.push(evt.data)
        }

        mediaRecorder.onstop = function () {
            console.log('停止录制')
            console.log(data)

            // 将一组数据生成一个统一的数据
            var title = document.querySelector('#title').value.trim()
            var type = "audio/ogg; codecs=opus"
            var blob = new Blob(data, {
                type: type
            })

            var url = URL.createObjectURL(blob);
            console.log(url)

            var oAudio = document.querySelector('audio')
            oAudio.src = url

            upload(title, blob)
        }

        document.querySelector('#stop').onclick = function () {
            mediaRecorder.stop()
        }

        mediaRecorder.start(1000)

        // setTimeout(function () {
        //     mediaRecorder.stop()
        // }, 10 * 1000)

    }

    function onError(error) {
        alert("麦克风授权失败" + error)
    }

    promise.then(onSuccess).catch(onError)
}